// 发送随机推荐请求
$.ajax({
  type: 'get',
  url: '/posts/random',
  success: function (response) {
    var temp = `
        {{each data}}
        <li>
            <a href="detail.html?id={{$value._id}}">
              <p class="title">{{$value.title}}</p>
              <p class="reading">阅读({{$value.meta.views}})</p>
              <div class="pic">
                <img src="{{$value.thumbnail ||  './uploads/upload_cb7ae004ba4dd89c32bb23110ef60e92.png'}}" alt="">
              </div>
            </a>
        </li>
        {{/each}}
        `
    var html = template.render(temp, {
      data: response
    })
    $('#publicBox').html(html)
  }
})

// 发送评论请求
$.ajax({
  type: 'get',
  url: '/comments/lasted',
  success: function (response) {
    var temp = `
        {{each data}}
			<li>
			  <a href="javascript:;">
			    <div class="avatar">
			      <img src="{{$value.author.avatar}}" alt="">
			    </div>
			    <div class="txt">
			      <p>
			        <span>{{$value.author.nickName}}</span>{{$imports.formdate($value.createAt)}}说:
			      </p>
			      <p>{{$value.content}}</p>
			    </div>
			  </a>
			</li>
			{{/each}}
        `
    var html = template.render(temp, {
      data: response
    })
    $('#commentBox').html(html)
  }
})

// 发送文章分类请求
$.ajax({
  type: 'get',
  url: '/categories',
  success: function (response) {
    var temp = `
      {{each data}}
			<li>
				<a href="list.html?categoryId={{$value._id}}">
					<i class="fa {{$value.className}}"></i>{{$value.title}}
				</a>
			</li>
			{{/each}}
      `
    var html = template.render(temp, {
      data: response
    })
    $('#navBox').html(html)
    $('#topNavBox').html(html)
  }
})


//处理日期格式
function formdate(date) {
  date = new Date(date)
  return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
};

//页面搜索功能
$('.search form').on('submit', function () {
	var key = $(this).find('.keys').val().replace(/\s/g, '');

  if (key.length == 0) {
    alert('请输入搜索内容')
    return false
  }
  location.href = `search.html?key=${key}`  
  
  return false
})